package scheduler

import "cn.hughie/learngo/crawler1/engine"

type QueueScheduler struct {
	workChan chan engine.Request
	send     chan chan engine.Request
}

func (s *QueueScheduler) WorkerReady(rc chan engine.Request) {
	s.send <- rc
}

func (s *QueueScheduler) Submit(r engine.Request) {
	s.workChan <- r
}

func (s *QueueScheduler) WorkChan() chan engine.Request {
	return make(chan engine.Request)
}

func (s *QueueScheduler) Run() {
	s.workChan = make(chan engine.Request)
	s.send = make(chan chan engine.Request)
	//q
	go func() {
		var in []engine.Request
		var out []chan engine.Request
		for {
			var activeRequest engine.Request
			var activeSendChan chan engine.Request
			if len(in) > 0 && len(out) > 0 {
				activeRequest = in[0]
				activeSendChan = out[0]
			}
			select {
			case send := <-s.send:
				out = append(out, send)
			case r := <-s.workChan:
				in = append(in, r)
			case activeSendChan <- activeRequest:
				in = in[1:]
				out = out[1:]
			}
		}
	}()

}
